#!/bin/bash

if [ $# -eq 0 ]; then
   echo "please input you domain name, usage: ./key-generage.sh organization yourdomain.com"
   exit 1
fi

ORG=$1
DOMAIN_NAME=$2

openssl genrsa -out ca.key 4096
openssl req -x509 -new -nodes -sha512 -days 3650 \
 -subj "/C=CN/ST=Beijing/L=Beijing/O=${ORG}/OU=Personal/CN=${DOMAIN_NAME}" \
 -key ca.key \
 -out ca.crt

openssl genrsa -out ${DOMAIN_NAME}.key 4096
openssl req -sha512 -new \
    -subj "/C=CN/ST=Beijing/L=Beijing/O=example/OU=Personal/CN=${DOMAIN_NAME}" \
    -key ${DOMAIN_NAME}.key \
    -out ${DOMAIN_NAME}.csr

cat > v3.ext <<-EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1=${DOMAIN_NAME}
DNS.2=${ORG}
EOF

openssl x509 -req -sha512 -days 3650 \
    -extfile v3.ext \
    -CA ca.crt -CAkey ca.key -CAcreateserial \
    -in ${DOMAIN_NAME}.csr \
    -out ${DOMAIN_NAME}.crt

openssl x509 -inform PEM -in ${DOMAIN_NAME}.crt -out ${DOMAIN_NAME}.cert

mkdir -p /etc/docker/certs.d/${DOMAIN_NAME}

cp ${DOMAIN_NAME}.cert /etc/docker/certs.d/${DOMAIN_NAME}/
cp ${DOMAIN_NAME}.key /etc/docker/certs.d/${DOMAIN_NAME}/
cp ca.crt /etc/docker/certs.d/${DOMAIN_NAME}/

echo "Verify the HTTPS Connection"
echo "On a machine that runs the Docker daemon, check the /etc/docker/daemon.json file to make sure that the -insecure-registry option is not set for https://${DOMAIN_NAME}"
docker login ${DOMAIN_NAME}
